package cn.edu.sjtu.se.dslab.dao.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import cn.edu.sjtu.se.dslab.action.bean.PageBean;
import cn.edu.sjtu.se.dslab.component.aadl.AADLModel;
import cn.edu.sjtu.se.dslab.dao.IAADLModelDao;
import cn.edu.sjtu.se.dslab.dao.IBaseDao;
import cn.edu.sjtu.se.dslab.exception.DBException;
import cn.edu.sjtu.se.dslab.util.Const;
import cn.edu.sjtu.se.dslab.util.MD5;


@Repository("aadlModelDao")
public class AADLModelDaoImpl implements IAADLModelDao {
	private static final String URI = "uri";

	@Resource(name = "baseDao")
	private IBaseDao<AADLModel> baseDao;
	@Override
	public void save(AADLModel aadlModel) {
		// TODO Auto-generated method stub
		String temp = "aadl_model"+System.currentTimeMillis();
		MD5 md5 = new MD5();
		String uri = md5.getMD5ofStr(temp).substring(0, 8);
		while (!checkUri(Const.URI_AADL_MODEL + ":" +uri)) {
			temp = "aadl_model"+System.currentTimeMillis();
			uri = md5.getMD5ofStr(temp).substring(0, 8);
		}
		aadlModel.setUri(Const.URI_AADL_MODEL + ":" +uri);
		baseDao.save(aadlModel);
	}

	@Override
	public boolean delete(AADLModel aadlModel) {
		// TODO Auto-generated method stub
		baseDao.delete(aadlModel);
		return true;
	}

	@Override
	public boolean deleteById(long id) {
		// TODO Auto-generated method stub
		baseDao.delById(AADLModel.class, id);
		return true;
	}

	@Override
	public boolean deleteByUri(String uri) {
		// TODO Auto-generated method stub
		AADLModel aadlModel = queryByUri(uri);
		baseDao.delete(aadlModel);
		return true;
	}

	@Override
	public void update(AADLModel aadlModel) {
		// TODO Auto-generated method stub
		baseDao.update(aadlModel);
	}

	@Override
	public PageBean<AADLModel> queryByPageNum(int pageNo) throws DBException {
		// TODO Auto-generated method stub
		PageBean<AADLModel> bean = baseDao.queryByHqlForPage(pageNo,
				Const.PAGESIZE, "AADLModel");
		return bean;
	}

	@Override
	public AADLModel queryById(long id) {
		// TODO Auto-generated method stub
		return baseDao.queryById(AADLModel.class, id);
	}

	@Override
	public AADLModel queryByUri(String uri) {
		// TODO Auto-generated method stub
		StringBuffer hql = new StringBuffer();
		// 拼接sql语句
		hql.append("from AADLModel where ");
		hql.append(URI + "=");
		hql.append("'" + uri + "'");
		return baseDao.queryObject(hql.toString());
	}

	@Override
	public boolean checkUri(String uri) {
		// TODO Auto-generated method stub
		AADLModel aadlModel = queryByUri(uri);
		if (aadlModel != null) {
			return false;
		} else {
			return true;
		}
	}

}
